package com.application.common.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObjectSummary;
import com.jfinal.kit.PropKit;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/8/29 0029.
 */
public class OssUtil {

    // endpoint以杭州为例，其它region请按实际情况填写
    public static String endpoint = PropKit.get("oss.endpoint", "http://oss-cn-shenzhen.aliyuncs.com");
    public static String key = PropKit.get("oss.key");
    public static String secret = PropKit.get("oss.secret");
    public static String bucket = PropKit.get("oss.bucket");

    public static String getOssPrefix(){
        return endpoint.replace("//", "//" + bucket + ".");
    }


    public static void upload(FileInputStream inputStream, String fileName) {
// 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, key, secret);
// 上传文件流
        ossClient.putObject(bucket, fileName, inputStream);
// 关闭client
        ossClient.shutdown();

    }

    public static void upload(String localFilePath, String fileName) {
// 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, key, secret);
// 上传文件流
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(localFilePath);
            ossClient.putObject(bucket, fileName, inputStream);
// 关闭client
            ossClient.shutdown();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

    public static List<List<String>> getPicList(List<String> picList) {
        OSSClient ossClient = new OSSClient(endpoint, key, secret);
        List<List<String>> lists = new ArrayList<>();

        for (String pic : picList) {
            List<OSSObjectSummary> summaries = ossClient.listObjects(bucket, pic).getObjectSummaries();
            List<String> list = new ArrayList<>();
            summaries.forEach(o -> {
                if (!o.getKey().endsWith("/")) {
                    list.add(o.getKey());
                }
            });
            lists.add(list);
        }

        return lists;
    }

    public static void delete(String fileName) {
// 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, key, secret);
      // 删除Object
        ossClient.deleteObject(bucket, fileName.startsWith("/") ? fileName.substring(1) : fileName);
    }
}
